package tgeo.common;

import java.net.InetSocketAddress;


import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IdleStatus;

import org.apache.mina.common.IoHandler;

import org.apache.mina.common.IoSession;
import org.apache.mina.transport.socket.nio.DatagramConnector;

public class UDPClient {

	public ConnectFuture connFuture = null;
	public UDPClient() {


	}
	public void connect(String host, int port, IoHandler handler) throws Exception{
		DatagramConnector connector = new DatagramConnector();
//		connector.setWorkerTimeout(5000);
		connFuture = connector.connect(new InetSocketAddress(
				host, port), handler);
//		IoSession session = connFuture.getSession();
//		IoHandler handler = session.getHandler();

	}
	public ConnectFuture getConnectFuture(){
		return connFuture;
		
	}
	public void close(){
		connFuture.getSession().close();
	}
	public void send(byte [] msg){
		ByteBuffer buf = ByteBuffer.allocate(msg.length);
		buf.put(msg);
		buf.flip();
		connFuture.getSession().write(buf);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		UDPClient client = new UDPClient();
		try {
			client.connect("192.168.123.100", 1470,new IoHandler() {

				@Override
				public void exceptionCaught(IoSession arg0, Throwable arg1)
						throws Exception {
				}

				@Override
				public void messageReceived(IoSession session, Object message)
						throws Exception {

					ByteBuffer buf = (ByteBuffer) message;
					byte[] bytearr = new byte[buf.remaining()];
					buf.get(bytearr);
					System.out.println(new String(bytearr));

				}

				@Override
				public void messageSent(IoSession session, Object message)
						throws Exception {

				}

				@Override
				public void sessionClosed(IoSession arg0) throws Exception {

				}

				@Override
				public void sessionCreated(IoSession arg0) throws Exception {

				}

				@Override
				public void sessionIdle(IoSession arg0, IdleStatus arg1)
						throws Exception {

				}

				@Override
				public void sessionOpened(IoSession arg0) throws Exception {

				}

			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
